//
//  SHComposeViewController.swift
//  SHWeibo
//
//  Created by jingming wang on 16/8/3.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit
import SVProgressHUD

class SHComposeViewController: UIViewController {
    
    // MARK: - 懒加载控件
    // 自定义titleView
    private lazy var titleView: SHTitleViewLabel = SHTitleViewLabel()
    // 配图
    private lazy var composePictureView: SHComposePictureView = {
        let view = SHComposePictureView()
        // 监听配图中加号cell点击 弹出相册
        view.closure = {[weak self] in
            self?.selectImage()
        }
        return view
    }()
    // 自定义textView
    //  在ios7 以后 如果系统检测到有导航栏 直接帮textView 的输入文字向下移动
    private lazy var composeTextView: SHComposeTextView = {
        let view = SHComposeTextView()
        view.delegate = self
        return view
    }()
    // 底部工具栏
    private lazy var composeToolbarView: SHComposeToolbarView = {
        let view = SHComposeToolbarView()
        view.closure = { [weak self] (type: SHComposeToolbarViewType)->() in
            switch type{
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyboard()
            case .Add:
                print("+")
            }
        }
        
        return view
    }()
    // 自定义表情键盘
    private lazy var emoticonKeyboardView: SHEmoticonKeyboardView = SHEmoticonKeyboardView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", target: self, action: "sendAction")
        
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
        
        setupUI()
        
        // 监听键盘frame的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 表情键盘删除按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButton", name: WBEmoticonDeleteButtonNoti, object: nil)
        // 表情键盘按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtons:", name: WBEmoticonButtonsNoti, object: nil)
        
    }
    
    // MARK: - 键盘frame改变监听方法
    @objc private func keyboardWillChangeFrame(noti: NSNotification){
        guard let userInfo = noti.userInfo else {
            return
        }
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        let value = userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        // 获取范围
        let rect = value.CGRectValue()
        self.composeToolbarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - K_SCREEN_HEIGHT)
        }
        // 设置动画
        UIView.animateWithDuration(Double(duration)) { () -> Void in
            self.composeToolbarView.layoutIfNeeded()
        }
    }
    
    // MARK: - 点击'表情'按钮
    @objc private func emoticonButtons(noti: NSNotification) {
        // 判断他是否为nil 而且是否可以转成Emoticon模型
        guard let emoticon = noti.object as? SHEmoticon else {
            return
        }
        // 如果是emoji表情
        if emoticon.type == "1" {
            // 十六进制字符串转格式
            let code = (emoticon.code ?? "" as NSString).emoji()
            composeTextView .insertText(code)
        }else {
            // 代表是图片表情
            // 获取当前composeTextView 的富文本
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            let lineHeight = composeTextView.font!.lineHeight
            let attr = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight)
            // 获取当前选中的光标
            let selectedRange = composeTextView.selectedRange
            // 替换文字
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            // 设置富文本属性
            allAttr.addAttributes([NSFontAttributeName: composeTextView.font!], range: NSRange(location: 0, length: allAttr.length))
            // 赋值
            composeTextView.attributedText = allAttr
            // 重新设置composeTextView选中光标
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            // 发送一个通知 告知textView 隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            // 主动调用代理方法 改变右侧按钮状态
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }
    
    // MARK: - 点击'删除'
    @objc private func emoticonDeleteButton() {
        composeTextView.deleteBackward()
    }
    
    // MARK: - 点击'取消'
    @objc private func cancelAction(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 点击'发布'
    @objc private func sendAction(){
        var allText = ""
        // 遍历获取所有文本输入
        /**
        *  遍历的结果
        *  遍历的范围
        *  遍历是否停止
        */
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) -> Void in
            // 如果是文本附件
            if let att = result["NSAttachment"] as? SHTextAttachment {
                allText += att.emoticon?.chs ?? ""
            }else {
                // 代表是文字
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                allText += str
            }
        }
        // 发送微博
        composePictureView.imageList.count > 0 ? uploadPic(allText) : uploadText(allText)
    }
    
    // MARK: - 设置界面
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        view.addSubview(composeTextView)
        composeTextView.addSubview(composePictureView)
        view.addSubview(composeToolbarView)
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: K_SCREEN_WIDTH - 20, height: K_SCREEN_WIDTH - 20))
            make.top.equalTo(composeTextView).offset(K_SCREEN_HEIGHT-K_SCREEN_WIDTH-44-44-10)
            make.centerX.equalTo(composeTextView)
        }
        
        composeToolbarView.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(44)
            make.leading.trailing.bottom.equalTo(view)
        }
    }
    // MARK: - 移除通知
    deinit {
        NSNotificationCenter.defaultCenter() .removeObserver(self)
    }
}

// MARK: - 底部视图按钮点击回调
extension SHComposeViewController {
    // 打开相册
    func selectImage(){
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    
    // 切换键盘
    func switchKeyboard() {
        // 如果inputView为nil 代表当前是系统键盘
        if composeTextView.inputView == nil {
            composeTextView.inputView = emoticonKeyboardView
            composeToolbarView.isEmoticon = true
        }else {
            // 反之代表自定义键盘
            composeTextView.inputView = nil
            composeToolbarView.isEmoticon = false
        }
        // 刷新
        composeTextView.reloadInputViews()
        // 设置第一响应者
        composeTextView.becomeFirstResponder()
    }
}

// MARK: - ImagePickerControllerDelegate
extension SHComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        composePictureView.addImages(image.getScaledImage(600))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

// MARK: - TextViewDelegate
extension SHComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        // textView中有文字才能发布
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 取消第一响应
        self.composeTextView.resignFirstResponder()
    }
    
}

// MARK: - 发送微博
extension SHComposeViewController {
    // 发送文字微博
    private func uploadText(status: String) {
        SHNetworkTools.sharedTools.composeUploadText(status, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    // 发送图片微博
    private func uploadPic(status: String) {
        SHNetworkTools.sharedTools.composeUploadPic(status, imageList: composePictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
}


